package io.kiki.sba.registry.server.metadata.multi.cluster;

import io.kiki.sba.registry.api.exchange.message.Response;
import io.kiki.sba.registry.server.metadata.multi.cluster.remote.RemoteClusterSlotSyncRequest;
import lombok.extern.slf4j.Slf4j;

@Slf4j
final class RemoteClusterSlotSyncTask implements Runnable {
    final long startTimestamp = System.currentTimeMillis();
    final String dataCenter;
    final long slotsEpoch;
    private final MultiClusterSlotsSyncerImpl multiClusterSlotMapSyncer;

    public RemoteClusterSlotSyncTask(MultiClusterSlotsSyncerImpl multiClusterSlotMapSyncer, String dataCenter, long slotsEpoch) {
        this.multiClusterSlotMapSyncer = multiClusterSlotMapSyncer;
        this.dataCenter = dataCenter;
        this.slotsEpoch = slotsEpoch;
    }

    @Override
    public void run() {
        boolean success = false;
        RemoteClusterSlotSyncRequest remoteClusterSlotSyncRequest = new RemoteClusterSlotSyncRequest(dataCenter, slotsEpoch);
        try {
            Response response = multiClusterSlotMapSyncer.remoteClusterMetaExchanger.sendRequest(dataCenter, remoteClusterSlotSyncRequest);

            // learn latest meta leader and slot table
            multiClusterSlotMapSyncer.handleSyncResponse(remoteClusterSlotSyncRequest, response.getResult());
            success = true;
        } catch (Throwable t) {
            multiClusterSlotMapSyncer.handleSyncFail(remoteClusterSlotSyncRequest, t);
        } finally {
            log.info("{},{},{},span={}", success ? 'Y' : 'N', dataCenter, slotsEpoch, System.currentTimeMillis() - startTimestamp);
        }
    }


}
